﻿import re
import logging

from functools import wraps
from django.http import HttpResponse, HttpResponseRedirect
from django.template import Context, loader
from django.shortcuts import render_to_response

from google.appengine.api import users


# ############################################################################################################
admin_emails = set(['ldmiao@gmail.com'])

def requires_admin(method):
    @wraps(method)
    def wrapper(*args, **kwargs):
        global admin_emails
        user = users.get_current_user()
        if user and user.email():
            if user.email() in admin_emails:
                return method(*args, **kwargs)
        
        return HttpResponseRedirect(users.create_login_url(args[0].get_full_path()))
        
    return wrapper

def requires_login(method):
    @wraps(method)
    def wrapper(*args, **kwargs):
        global admin_emails
        user = users.get_current_user()
        if user and user.email():
            return method(*args, **kwargs)
        
        return HttpResponseRedirect(users.create_login_url(args[0].get_full_path()))
        
    return wrapper

# ##################################################################################################
def render(template, payload, mimetype=None):
    '''render the template with payload'''
    if mimetype is None:
        mimetype = "text/html"
    
    t = loader.get_template(template)
    c = Context(payload)
    
    return HttpResponse(t.render(c), mimetype=mimetype)
    #return render_to_response(template, payload, mimetype=mimetype)

def getAllUsers():
    '''get all the users order by the last access'''
    return models.User.all().order('-last_update')

def getUser(email="anonymous@gmail.com"):
    '''get all the current user, if not exist, return anonymous'''
    user = users.get_current_user()
    if not user:
        user = users.User(email)
    return user

def getLoginAndUrl(request):
    '''get toggled login and logout label and the url'''
    if users.get_current_user():
        url = users.create_logout_url(request.get_full_path())
        url_linktext = '注销'
    else:
        url = users.create_login_url(request.get_full_path())
        url_linktext = '登陆'
    return url_linktext, url
    
